// pages/vaild/vaild.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    phone:'',
    phoneHtml:'',
    code:'',
    time:'60',
    resendFlag:false
  },
  // 发送验证码的函数
  sendCode: function() {
    console.log(123456)
    let phone=this.data.phone;
    var that = this;
    // 调用后端API发送验证码
    wx.request({
      url: app.globalData.onlineUrl+'/login/validcode', 
      method: 'GET',
      data: {
        phone:phone
      },
      success: function(res) {
        // 成功处理
        console.log('验证码发送成功', res);
        // 开始计时器，按钮不可点击
        that.startTimer();
      },
      fail: function(err) {
        // 错误处理
        console.error('验证码发送失败', err);
      },
      complete: function() {}
    });
  },
  // 开始计时器，禁用按钮
  startTimer: function() {
    var that = this;
    console.log(888,that.data.time)
    that.setData({
      resendFlag:false
    });
    var interval = setInterval(function() {
      var time = that.data.time - 1;
      if (time <= 0) {
        clearInterval(interval);
        that.setData({
          time: 60,
          resendFlag:true
        });
      } else {
        that.setData({
          time: time
        });
      }
    }, 1000);
    that.setData({ interval: interval });
  },
  inputChange(e){
    let _this=this;
    if(e.detail.value.length==4){
      let openId=wx.getStorageSync('openid');
      //提交验证码
      wx.request({
        url: app.globalData.onlineUrl+'/login', 
        method: 'GET',
        data: {
          phone:_this.data.phone,
          code:e.detail.value,
          openId:openId
        },
        success: function(res) {
          console.log()
          if(res.data.code==1){
            console.log('登陆成功', res.data.data);
            wx.setStorageSync('phone', res.data.data.phone);
            wx.setStorageSync('openid', res.data.data.openId);
            wx.setStorageSync('uid', res.data.data.uid);
            wx.switchTab({
              url: '/pages/index/index'
            })
          }else{
            console.log('登陆失败', res);
            wx.showToast({
              title: "请输入正确的验证码",
              icon: 'none',
            });
          }
        },
        fail: function(err) {
        },
        complete: function() {}
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      phone:options.phone,
      phoneHtml:options.phone.substr(0,3)+' '+options.phone.substr(3,4)+' '+options.phone.substr(7,4)
    })
    this.sendCode();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})